# -*- coding: utf-8 -*-
# @Time    : 2018-05-22 21:43
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : Ind_OverdueMon_2YrCheck.py
# @Software: PyCharm

'''eof
name:贷款2年内累计逾期月份数
code:Ind_OverdueMon_2YrCheck
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
import re
import datetime
import traceback
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']


def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def ConvertDataType(dataValue, dataType):
    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'int':
        try:
            returnData = int(dataValue) if int(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    return returnData


def Ind_OverdueMon_2YrPre(*arg):
    try:
        # 两年之前(year*12+month)
        monthTwoYearsAgo = (datetime.datetime.now().year - 2) * 12 + datetime.datetime.now().month
        monthToday = (datetime.datetime.now().year) * 12 + datetime.datetime.now().month
        dk = 0
        # 逾期信息
        icrLoanInfo002Loan_list = FormatData(arg[0])
        # 逾期记录明细
        icrLatest5YearOverdueDetailLoanList = FormatData(arg[1])
        if icrLoanInfo002Loan_list == [{}]  and icrLatest5YearOverdueDetailLoanList == [{}]:
            dk = None
        else:
            month24MaxDk = []
            # 取24个月还款状态最大数
            for icrLoanInfo002Loan in icrLoanInfo002Loan_list:
                try:
                    latest24StateLil = icrLoanInfo002Loan.get('Latest24State')
                    EndMonth = re.compile(r'\D+').sub('', icrLoanInfo002Loan.get('EndMonth'))
                    if latest24StateLil in null_type_list or EndMonth in null_type_list:
                        month24MaxDk.append(None)
                        continue
                    EndMonhFact = float(EndMonth[:4]) * 12 + float(EndMonth[4:6]) if float(EndMonth[4:6]) <= 12 else float(
                        EndMonth[4:5])
                    latest24StateLilSub = latest24StateLil[::-1]
                    for i, state in enumerate(latest24StateLilSub):
                        if re.compile(r'\d').match(state) and float(state) >= 1 and float(state) <= 7:
                            if arg[0] == "ICRStdLoancardInfo002*Std":
                                if float(state) > 2:
                                    for j in range(int(float(state)) - 2):
                                        month24MaxDk.append(EndMonhFact - i- j)
                                else:
                                    month24MaxDk.append("None")
                            else:
                                for j in range(int(float(state))):
                                    month24MaxDk.append(EndMonhFact - i - j)
                        else:
                            month24MaxDk.append("None")
                except:
                    month24MaxDk.append(None)
                    continue
            # 取2年内持续逾期最大数
            for icrLatest5YearOverdueDetailLoan in icrLatest5YearOverdueDetailLoanList:
                try:
                    month =  re.compile(r'\D+').sub('', icrLatest5YearOverdueDetailLoan.get('Month'))
                    monthFact = float(month[:4]) * 12 + float(month[4:6]) if float(month[4:6]) <= 12 else float(month[4:5])
                    lastMonths = ConvertDataType(ConvertDataType(icrLatest5YearOverdueDetailLoan.get('LastMonths')
                                                                 , 'float'), 'int')
                    if month in null_type_list or monthFact > monthToday or monthFact in null_type_list \
                            or lastMonths in null_type_list:
                        month24MaxDk.append(None)
                        continue
                    if lastMonths >= 1 and lastMonths <= 7:
                        if monthFact > monthTwoYearsAgo:
                            if arg[0] == "ICRStdLoancardInfo002*Std":
                                if lastMonths > 2:
                                    for lastMonth in range(0, lastMonths-2):
                                        monthSub = monthFact - lastMonth
                                        month24MaxDk.append(monthSub)
                                else:
                                    month24MaxDk.append("None")
                            else:
                                for lastMonth in range(0, lastMonths):
                                    monthSub = monthFact - lastMonth
                                    month24MaxDk.append(monthSub)
                        else:
                            month24MaxDk.append("None")
                    else:
                        month24MaxDk.append(None)
                except:
                    month24MaxDk.append(None)
                    continue
            month24MaxDkNotNone = filter(lambda x: x is not None, month24MaxDk)
            month24MaxNotNoneStr = filter(lambda x: x != 'None', month24MaxDkNotNone)
            if len(month24MaxDkNotNone) == 0:
                dk = None
            elif len(month24MaxNotNoneStr) == 0:
                dk = []
            else:
                dk = map(float, month24MaxNotNoneStr)
        return dk
    except:
        print traceback.format_exc()
        return u"缺失值"


def Ind_OverdueMon_2YrCheck():
    # 贷款逾期信息
    dk = Ind_OverdueMon_2YrPre(*("ICRLoanInfo002*Loan", "ICRLatest5YearOverdueDetail*Loan"))
    # 贷记卡逾期信息
    djk = Ind_OverdueMon_2YrPre(*("ICRLoancardInfo002*Card", "ICRLatest5YearOverdueDetail*Card"))
    # 准贷记卡逾期信息
    zdjk = Ind_OverdueMon_2YrPre(*("ICRStdLoancardInfo002*Std", "ICRLatest5YearOverdueDetail*Std"))
    if zdjk is None and djk is None and dk is None:
        return u"缺失值"
    zdjk = zdjk if zdjk is not None else []
    djk = djk if djk is not None else []
    dk = dk if dk is not None else []
    return len(set(zdjk + djk + dk))


result = Ind_OverdueMon_2YrCheck()